<template>
    <v-autocomplete 
        v-model="selectedValue" 
        :items="filteredUsers" 
        item-title="realName" 
        item-value="id" 
        :label="label"
        :placeholder="placeholder" 
        :variant="variant" 
        :density="density" 
        :clearable="clearable" 
        :disabled="disabled"
        :loading="userStore.usersLoading" 
        :error-messages="errorMessages" 
        :prepend-inner-icon="prependInnerIcon"
        :append-inner-icon="appendInnerIcon" 
        :class="customClass" 
        @update:model-value="handleValueChange"
        @update:search="handleSearch" 
        :return-object="!multiple"
        :search="searchQuery" 
        :menu-props="{ maxHeight: '300px' }"
        :multiple="multiple"
        :chips="multiple"
        :closable-chips="multiple"
        no-filter
    >
        <!-- 自定义选项显示 -->
        <template v-slot:item="{ props: itemProps, item }">
            <v-list-item v-bind="itemProps" class="user-option-item">
                <template v-slot:prepend>
                    <v-avatar size="32" class="mr-3" :color="!item.raw.avatar ? 'primary' : undefined">
                        <v-img v-if="item.raw.avatar" :src="item.raw.avatar" :alt="item.raw.realName" cover />
                        <span v-else class="text-white font-weight-bold">
                            {{ item.raw.realName.charAt(0) }}
                        </span>
                    </v-avatar>
                </template>

                <!-- <v-list-item-title>{{ item.raw.realName }}</v-list-item-title> -->
                <v-list-item-subtitle class="text-caption text-grey">
                    {{ item.raw.email }}
                </v-list-item-subtitle>
            </v-list-item>
        </template>

        <!-- 自定义chip显示（多选模式） -->
        <template v-slot:chip="{ props, item }">
            <v-chip
                v-bind="props"
                :prepend-avatar="item.raw.avatar"
                :text="item.raw.realName"
                size="small"
            ></v-chip>
        </template>

        <!-- 自定义选中项显示（单选模式） -->
        <template v-slot:selection="{ item }">
            <div v-if="!multiple" class="d-flex align-center">
                <v-avatar size="24" class="mr-2" :color="!item.raw.avatar ? 'primary' : undefined">
                    <v-img v-if="item.raw.avatar" :src="item.raw.avatar" :alt="item.raw.realName" cover />
                    <span v-else class="text-white font-weight-bold text-caption">
                        {{ item.raw.realName.charAt(0) }}
                    </span>
                </v-avatar>
                <div class="user-selection-info">
                    <div class="text-body-2 font-weight-medium">{{ item.raw.realName }}</div>
                    <div class="text-caption text-grey" v-if="showEmailInSelection">
                        {{ item.raw.email }}
                    </div>
                </div>
            </div>
        </template>

        <!-- 无数据时的显示 -->
        <template v-slot:no-data>
            <v-list-item>
                <v-list-item-title class="text-center text-grey">
                    <v-icon class="mr-2">mdi-account-search</v-icon>
                    {{ searchQuery ? 'No Found' : 'No Data' }}
                </v-list-item-title>
            </v-list-item>
        </template>
    </v-autocomplete>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import type { UserInfo } from '@/store/user';

// 用户数据类型定义已在store中定义，直接导入使用

// Props 定义
interface Props {
    modelValue?: UserInfo | string | null | UserInfo[] | string[];
    label?: string;
    placeholder?: string;
    variant?: 'filled' | 'outlined' | 'underlined' | 'plain' | 'solo' | 'solo-inverted' | 'solo-filled';
    density?: 'default' | 'comfortable' | 'compact';
    clearable?: boolean;
    disabled?: boolean;
    errorMessages?: string | string[];
    prependInnerIcon?: string;
    appendInnerIcon?: string;
    customClass?: string;
    showEmailInSelection?: boolean;
    filterByDepartment?: string;
    filterByStatus?: 'active' | 'inactive' | 'all';
    excludeUsers?: string[]; // 排除特定用户ID
    includeUsers?: string[]; // 只包含特定用户ID
    multiple?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
    label: '选择用户',
    placeholder: '请选择用户',
    variant: 'outlined',
    density: 'comfortable',
    clearable: true,
    disabled: false,
    showEmailInSelection: false,
    filterByStatus: 'all',
    multiple: false
});

// Emits 定义
const emit = defineEmits<{
    'update:modelValue': [value: UserInfo | string | null | UserInfo[] | string[]];
    'user-selected': [user: UserInfo | null];
    'user-selected-list': [user: UserInfo[]];
    'search': [query: string];
}>();

// 使用用户store
const userStore = useUserStore();

// 响应式数据
const searchQuery = ref('');
const selectedUser = ref<UserInfo | null>(null);
const selectedUsers = ref<UserInfo[]>([]);

// 防抖定时器
let searchTimeout: number | null = null;

// 计算属性 - 当前选中的值（用于v-model）
const selectedValue = computed({
    get() {
        if (props.multiple) {
            return selectedUsers.value.map(user => user.id);
        } else {
            return selectedUser.value?.id || null;
        }
    },
    set(value) {
        if (props.multiple) {
            // 多选模式：value是ID数组
            if (Array.isArray(value)) {
                selectedUsers.value = value.map(id => 
                    userStore.allUsers.find(user => user.id === id)
                ).filter(Boolean) as UserInfo[];
            } else {
                selectedUsers.value = [];
            }
        } else {
            // 单选模式：value是单个ID
            if (typeof value === 'string') {
                selectedUser.value = userStore.allUsers.find(user => user.id === value) || null;
            } else {
                selectedUser.value = null;
            }
        }
    }
});

// 计算属性 - 过滤后的用户列表
const filteredUsers = computed(() => {
    let users = [...userStore.allUsers];

    // 按部门过滤
    if (props.filterByDepartment) {
        users = users.filter(user => user.department === props.filterByDepartment);
    }

    // 按状态过滤
    if (props.filterByStatus !== 'all') {
        users = users.filter(user => user.status === props.filterByStatus);
    }

    // 排除特定用户
    if (props.excludeUsers && props.excludeUsers.length > 0) {
        users = users.filter(user => !props.excludeUsers!.includes(user.id));
    }

    // 只包含特定用户
    if (props.includeUsers && props.includeUsers.length > 0) {
        users = users.filter(user => props.includeUsers!.includes(user.id));
    }

    // 搜索过滤
    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        users = users.filter(user =>
            user.realName.toLowerCase().includes(query) ||
            user.email.toLowerCase().includes(query) ||
            (user.department && user.department.toLowerCase().includes(query)) ||
            (user.position && user.position.toLowerCase().includes(query))
        );
    }

    // 为每个用户添加显示文本
    return users.map(user => ({
        ...user
    }));
});

// 监听 modelValue 变化
watch(() => props.modelValue, (newValue) => {
    if (props.multiple) {
        // 多选模式
        if (Array.isArray(newValue)) {
            if (typeof newValue[0] === 'string') {
                // 字符串ID数组
                selectedUsers.value = newValue.map(id => 
                    userStore.allUsers.find(user => user.id === id)
                ).filter(Boolean) as UserInfo[];
            } else {
                // UserInfo对象数组
                selectedUsers.value = newValue as UserInfo[];
            }
        } else {
            selectedUsers.value = [];
        }
    } else {
        // 单选模式（保持原有逻辑）
        if (typeof newValue === 'string') {
            // 如果传入的是用户ID字符串，查找对应的用户对象
            const user = userStore.allUsers.find(user => user.id === newValue);
            selectedUser.value = user || null;
        } else {
            selectedUser.value = newValue as UserInfo || null;
        }
    }
}, { immediate: true });

// 处理值变化
function handleValueChange(value: any) {
    if (props.multiple) {
        // 多选模式
        if (Array.isArray(value)) {
            selectedUsers.value = value.map(id => 
                userStore.allUsers.find(user => user.id === id)
            ).filter(Boolean) as UserInfo[];
        } else {
            selectedUsers.value = [];
        }
        emit('update:modelValue', selectedUsers.value.map(user => user.id));
        emit('user-selected-list', selectedUsers.value);
    } else {
        // 单选模式（保持原有逻辑）
        if (typeof value === 'string') {
            selectedUser.value = userStore.allUsers.find(user => user.id === value) || null;
        } else {
            selectedUser.value = value;
        }
        emit('update:modelValue', selectedUser.value);
        emit('user-selected', selectedUser.value);
    }
}

// 处理用户选择（单选模式）
function handleUserSelect(user: UserInfo | null) {
    selectedUser.value = user;
    emit('update:modelValue', user);
    emit('user-selected', user);
}

// 处理搜索
function handleSearch(query: string) {
    // 清除之前的定时器
    if (searchTimeout) {
        clearTimeout(searchTimeout);
    }

    // 设置防抖延迟
    searchTimeout = setTimeout(() => {
        searchQuery.value = query || '';
        emit('search', searchQuery.value);
    }, 150);
}

// 初始化数据（如果需要的话）
async function initializeUsers() {
    // 如果store中没有用户数据，尝试加载
    if (userStore.allUsers.length === 0 && !userStore.usersLoading) {
        console.log('SelectUser: 用户列表为空，尝试加载...');
        await userStore.loadAllUsers();
    } else if (userStore.shouldRefreshUsers()) {
        console.log('SelectUser: 用户列表需要刷新...');
        await userStore.loadAllUsers();
    }
}

// 公开的方法
const refresh = () => {
    userStore.loadAllUsers();
};

const clearSelection = () => {
    if (props.multiple) {
        selectedUsers.value = [];
        emit('update:modelValue', []);
        emit('user-selected-list', []);
    } else {
        handleUserSelect(null);
    }
};

const getSelectedUser = () => {
    return props.multiple ? selectedUsers.value : selectedUser.value;
};

const getSelectedUsers = () => {
    return selectedUsers.value;
};

// 暴露给父组件的方法和数据
defineExpose({
    refresh,
    clearSelection,
    getSelectedUser,
    getSelectedUsers,
    allUsers: computed(() => userStore.allUsers),
    filteredUsers,
    loading: computed(() => userStore.usersLoading)
});

// 组件挂载时检查并初始化数据
onMounted(() => {
    initializeUsers();
});
</script>

<style scoped>
.user-option-item {
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;
}

.user-option-item:hover {
    background-color: rgba(var(--v-theme-primary), 0.04);
}

.user-option-item:last-child {
    border-bottom: none;
}

.user-selection-info {
    line-height: 1.2;
}

.user-selection-info .text-caption {
    margin-top: 1px;
}

/* 自定义滚动条 */
:deep(.v-overlay__content) {
    scrollbar-width: thin;
    scrollbar-color: rgba(0, 0, 0, 0.3) transparent;
}

:deep(.v-overlay__content::-webkit-scrollbar) {
    width: 6px;
}

:deep(.v-overlay__content::-webkit-scrollbar-track) {
    background: transparent;
}

:deep(.v-overlay__content::-webkit-scrollbar-thumb) {
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 3px;
}

:deep(.v-overlay__content::-webkit-scrollbar-thumb:hover) {
    background-color: rgba(0, 0, 0, 0.5);
}

/* 选中项样式优化 */
:deep(.v-field__input) {
    padding-top: 8px;
    padding-bottom: 8px;
}

/* 选项列表样式 */
:deep(.v-list-item-title) {
    font-weight: 500 !important;
}

:deep(.v-list-item-subtitle) {
    opacity: 0.7;
    font-size: 0.75rem;
}

/* 多选模式下的chip样式 */
:deep(.v-chip) {
    margin: 2px;
}

:deep(.v-chip .v-avatar) {
    margin-right: 4px;
}
</style>
